package com.hpjpw.idoapp.controller;

import com.hpjpw.ido.domain.Student;
import com.hpjpw.ido.service.IStudentService;
import com.hpjpw.idoapp.domain.UserUpdatePwdVo;
import com.hpjpw.idoapp.service.IDoTaskService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @BelongsProject: ruoyi
 * @BelongsPackage: com.hpjpw.idoapp.controller
 * @Author: hpj
 * @CreateTime: 2021-01-07 20:03
 * @Description: 系统用户表模块
 */
@RestController
@RequestMapping("/ido/app/user/profile")
public class IDoUserController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IStudentService studentService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IDoTaskService iDoTaskService;

    /**
     * 获取用户类信息
     */
    @ApiOperation("获取用户类信息")
    @GetMapping("/UserConstants/list")
    public AjaxResult getUserConstants() {
        AjaxResult success = AjaxResult.success();
        success.put("STUDENT_DEPT_ID", UserConstants.STUDENT_DEPT_ID);
        success.put("STUDENT_POST_ID", UserConstants.STUDENT_POST_ID);
        success.put("STUDENT_ROLE_ID", UserConstants.STUDENT_ROLE_ID);
        success.put("TEACHER_DEPT_ID", UserConstants.TEACHER_DEPT_ID);
        success.put("TEACHER_POST_ID", UserConstants.TEACHER_POST_ID);
        success.put("TEACHER_ROLE_ID", UserConstants.TEACHER_ROLE_ID);
        success.put("WORKER_DEPT_ID", UserConstants.WORKER_DEPT_ID);
        success.put("WORKER_POST_ID", UserConstants.WORKER_POST_ID);
        success.put("WORKER_ROLE_ID", UserConstants.WORKER_ROLE_ID);
        return success;
    }

    /**
     * 获取用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/{userId}")
    public AjaxResult getUserInfo(@PathVariable("userId") Long userId) {
        if (!iDoTaskService.isWorker())
            return AjaxResult.error("无此权限！");
        SysUser sysUser = userService.selectUserById(userId);
        if (StringUtils.isNull(sysUser))
            return AjaxResult.error("找不到该用户");
        AjaxResult success = AjaxResult.success();
        success.put("name", sysUser.getNickName());
        success.put("imgUrl", sysUser.getAvatar());
        return success;
    }

    /**
     * 学生修改企业ID
     */
    @ApiOperation("学生修改企业ID")
    @PostMapping("/student/enterpriseId")
    public AjaxResult modifyStudentEnterpriseId(Long enterpriseId) {
        Student student = studentService.selectStudentByUserID(SecurityUtils.getUserId());
        if (StringUtils.isNull(student))
            return AjaxResult.error("非学生用户无此权限");
        if (StringUtils.isNotNull(student.getEnterpriseId()) && !student.getEnterpriseId().equals(0L))
            return AjaxResult.error("企业ID已存在，若需修改请联系系统管理员");
        student.setEnterpriseId(enterpriseId);
        studentService.updateStudent(student);
        return AjaxResult.success("修改成功");
    }

    /**
     * 修改用户手机号
     */
    @ApiOperation("修改用户手机号")
    @Log(title = "修改用户手机号", businessType = BusinessType.UPDATE)
    @PutMapping("/phoneNumber")
    public AjaxResult updatePhoneNumber(String phoneNumber) {
        SysUser user = new SysUser();
        user.setPhonenumber(phoneNumber);
        user.setUserId(SecurityUtils.getUserId());
        if (userService.updateUserProfile(user) > 0) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setPhonenumber(phoneNumber);
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改手机号异常，请联系管理员");
    }

    /**
     * 修改用户性别
     */
    @ApiOperation("修改用户性别")
    @Log(title = "修改用户性别", businessType = BusinessType.UPDATE)
    @PutMapping("/sex")
    public AjaxResult updateSex(String sex) {
        SysUser user = new SysUser();
        user.setSex(sex);
        user.setUserId(SecurityUtils.getUserId());
        if (userService.updateUserProfile(user) > 0) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setSex(sex);
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改性别异常，请联系管理员");
    }

    /**
     * 修改用户邮箱
     */
    @ApiOperation("修改用户邮箱")
    @Log(title = "修改用户邮箱", businessType = BusinessType.UPDATE)
    @PutMapping("/email")
    public AjaxResult updateEmail(String email) {
        SysUser user = new SysUser();
        user.setEmail(email);
        user.setUserId(SecurityUtils.getUserId());
        if (userService.updateUserProfile(user) > 0) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setEmail(email);
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改邮箱异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(@RequestBody @Validated UserUpdatePwdVo updatePwdVo) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(updatePwdVo.getOldPassword(), password)) {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(updatePwdVo.getNewPassword(), password)) {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(updatePwdVo.getNewPassword())) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(updatePwdVo.getNewPassword()));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }
}
